function [ ] = plotFitTimeSeriesPrice( ctrTable, period, ...
                                            filename, optfig, originalPriceModelTable )
% Plot the time series of prices in the data and the counterfactual model,
%   to assess model fit.
%
%   INPUTS:
%     Pt - Price time series by compliance period
%     ctr - Counterfactual with market scenario
%     period - Table of scenarios to plot with variables
%                             id_period   cap
%          where id_period gives the cost estimates and cap the emissions
%          cap to be applied.
%     filename - File in which to save figure
%     optfig - Figure options

%% Setup data

% Pick out only the scenarios passed as arguments to plot
period = renamevars(period,'cap','id_level');
ctrTable = innerjoin(ctrTable,period,...
      'Keys',{'id_period','id_level'});
fprintf(1,'Plotting the clearing price for periods . . . \n');
display(ctrTable);

% Pull data from scenario table
t        = ctrTable.id_period;
Pt_model = ctrTable.Pt;
Pt_data  = ctrTable.price_clearing_mean;
Bt_data  = ctrTable.price_bid_mean;

%% Plot

% Lines
f0 = figure;
if nargin>4
    ctrTableNew = innerjoin(originalPriceModelTable,period,...
      'Keys',{'id_period','id_level'});
    l1 = plot( t, Pt_model, 'rs-',  'LineWidth',optfig.axisweight-0.5 ); hold on;
    l2 = plot( t, Pt_data,  'ko:',  'LineWidth',optfig.axisweight-0.5 );  
    l3 = plot( t, Bt_data,  'ko--', 'LineWidth',optfig.axisweight-0.5 );   
    l4 = plot( t, ctrTableNew.Pt,  'bo-', 'LineWidth',optfig.axisweight-0.5 );  
else
    % include errors
    if any(strcmp('Pt_lowCI',ctrTable.Properties.VariableNames))
        l1 = errorbar( t, Pt_model, ctrTable.Pt_lowCI,ctrTable.Pt_highCI,  'bo-',  'LineWidth',optfig.axisweight-0.5 ); hold on;
    else
        l1 = plot( t, Pt_model, 'bo-',  'LineWidth',optfig.axisweight-0.5 ); hold on;
    end
    l1 = plot( t, Pt_model, 'bo-',  'LineWidth',optfig.axisweight-0.5 ); hold on;
    l2 = plot( t, Pt_data,  'ko:',  'LineWidth',optfig.axisweight-0.5 );  
    l3 = plot( t, Bt_data,  'ko--', 'LineWidth',optfig.axisweight-0.5 );   
end
% Figure formatting
set(gcf, 'Color'       , 'w', ...
    'position',[0 0 500 500]);
set(gca, optfig.labProp{:}, ...
         'Box'         , 'off'             , ...
         'LineWidth'   , optfig.axisweight , ...
         'XTick'       , [1:1:10] );

% Axis labels
xlabel('Compliance period',optfig.textProp{:});
ylabel('Price (INR/kg)',optfig.textProp{:});

% Title
% titleString = sprintf('Model fit to time series of market-clearing prices');
% title(titleString,optfig.textProp{:},'Interpreter','latex');

% Axis limits must include zero
yl = ylim();
xl = xlim();
ylim([0 yl(2)]);
xlim([0 xl(2)]);

% If pass in comparison price path, add it to the graph
if nargin>4 
    legend([l1, l2, l3, l4] ,...
    {'Model: step-function MAC clearing price',...
    'Data: clearing price (period mean)',...
    'Data: bid price (period mean)', ...
    'Model: iso-elastic MAC clearing price'},...
    'Location','southoutside',...
    'Orientation','vertical',...
    optfig.legProp{:});
    legend boxoff;
else
    legend([l1, l2, l3] ,...
    {'Model: clearing price',...
    'Data: clearing price (period mean)',...
    'Data: bid price (period mean)'},...
    'Location','southoutside',...
    'Orientation','vertical',...
    optfig.legProp{:});
    legend boxoff;
end

hold off;

%% Export figure to file

% Crop whitespace 
fig = gcf;
fig.PaperPositionMode = 'auto';
fig.PaperSize = [8.8 6.6];
fig.PaperPosition = [0.25 0.10 8.3 6.95];

ax = gca;
ax.Position = [0.08 0.28 0.90 0.63];


% Save all figures
%[filepath, ~, ~] = fileparts(filename);
%if not(isfolder(filepath))
%    mkdir(filepath);
%end
%fprintf(1,'Writing %s to file ...\n',filename);
%print(f0,'-dpdf','-painters','-noui','-r600', filename);

% Save figure for specific model type and subtype
% Determine model type
if contains(filename, "Iso")
    type = "Iso";
    if contains(filename, "FullNoHet")
        subtype = "FullNoHet";
    else 
        subtype = "FullHet";
    end
else
    type = "Step";
    if contains(filename, "NoFreeCyc")
        subtype = "NoFreeCyc";
    else 
        subtype = "FreeCyc";
    end
end

% Get path
[~, old_file, old_ext] = fileparts(filename);
new_filepath = erase(filename, strcat("model/", type, "/", subtype, "/", old_file, old_ext));

if type == "Iso" && subtype == "FullNoHet"
    filename = strcat(new_filepath, "Figure_8");
    fprintf(1,'Writing %s to file ...\n',filename);
    print(f0,'-dpdf','-painters','-noui','-r600', filename);

elseif type == "Step" && subtype == "FreeCyc"
    filename = strcat(new_filepath, "Figure_E2");
    fprintf(1,'Writing %s to file ...\n',filename);
    print(f0,'-dpdf','-painters','-noui','-r600', filename);
end

end